package com.wty.app.bthcar.adapter;

import static com.lxj.xpopup.enums.PopupAnimation.ScrollAlphaFromTop;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gcssloop.view.utils.DensityUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.animator.ScrollScaleAnimator;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.wty.app.bthcar.R;
import com.wty.app.bthcar.bluetooth.DeviceListActivity;
import com.wty.app.bthcar.info.DeviceBean;

import java.util.ArrayList;
import java.util.Set;

public class DeviceDialog extends CenterPopupView {

    int REQUEST_ENABLE_BT = 1;
    // 蓝牙扫描时间
    private static final long SCAN_PERIOD = 10000;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        /* class com.wty.app.bluetoothcar.bluetooth.DeviceListActivity.AnonymousClass3 */

        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.bluetooth.device.action.FOUND".equals(action)) {
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                if (device.getBondState() != 12) {
                   mNewDevicesArrayAdapter.add(new DeviceBean(device.getName(),device.getAddress(),device.getType()));
                }
            } else if ("android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(action)) {
                if (loading.isShow()){
                    loading.dismiss();
                }
//               setProgressBarIndeterminateVisibility(false);
//               setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getItemCount() == 0) {
                   mNewDevicesArrayAdapter.add(new DeviceBean(getResources().getText(R.string.none_found).toString(),"",0));
                }
            }
        }
    };
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    private BluetoothAdapter mBtAdapter;
    private DeviceListAdapter.OnClickListener mDeviceClickListener = new DeviceListAdapter.OnClickListener() {
        @Override
        public void onClick(DeviceBean bean) {
           /* enableScan = true;
            if (mScanning) {
                *//* 停止扫描设备 *//*
                mBluetoothLeScanner.stopScan(mScanCallback);
                mScanning = false;
            }*/

            mBtAdapter.cancelDiscovery();
            if (itemListener!=null){
                itemListener.OnResult(bean);
            }
            dismiss();
        }
    };
    private DeviceListAdapter mNewDevicesArrayAdapter;
    private DeviceListAdapter deviceListAdapter;

    private OnItemListener itemListener;
    private LoadingPopupView loading;
    private BluetoothLeScanner mBluetoothLeScanner;
    private TextView scan;

    public DeviceDialog(@NonNull Context context,OnItemListener itemListener) {
        super(context);
        this.itemListener = itemListener;
    }

    public interface OnItemListener{
        void OnResult(DeviceBean deviceBean);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.device_list_pop;
    }

    @Override
    protected int getMaxWidth() {
        return DensityUtils.dip2px(getContext(),250);
    }

    // 描述扫描蓝牙的状态
    private boolean mScanning;//当前是否正在扫描
    private boolean enableScan;//当前是否可扫描
    ArrayList<DeviceBean> pairedList =new ArrayList<>();
    ArrayList<DeviceBean> newList =new ArrayList<>();



    @Override
    protected void onCreate() {
        super.onCreate();
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        deviceListAdapter = new DeviceListAdapter(pairedList);
        deviceListAdapter.setOnItemClickListener(this.mDeviceClickListener);

        loading = new XPopup.Builder(getContext()).asLoading("正在搜索蓝牙设备");
        RecyclerView pairedListView = findViewById(R.id.paired_devices);
        pairedListView.setLayoutManager(manager);
        pairedListView.setAdapter(deviceListAdapter);

        mNewDevicesArrayAdapter = new DeviceListAdapter(newList);
        mNewDevicesArrayAdapter.setOnItemClickListener(this.mDeviceClickListener);
        RecyclerView newDevicesListView =  findViewById(R.id.new_devices);
        LinearLayoutManager manager2 = new LinearLayoutManager(getContext());
        newDevicesListView.setLayoutManager(manager2);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);

        getContext().registerReceiver(this.mReceiver, new IntentFilter("android.bluetooth.device.action.FOUND"));
        getContext().registerReceiver(this.mReceiver, new IntentFilter("android.bluetooth.adapter.action.DISCOVERY_FINISHED"));

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
//        init_ble();
        scan = findViewById(R.id.button_scan_pop);
        scan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("getPrintDEEE","c");
                doDiscovery();
//                scanLeDevice(true);
                if (!loading.isShow()){
                    loading.show();
                }
            }
        });

        Set<BluetoothDevice> pairedDevices = this.mBtAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                this.deviceListAdapter.add(new DeviceBean(device.getName(),device.getAddress(),device.getType()));
            }
            return;
        }

        this.deviceListAdapter.add(new DeviceBean(getResources().getText(R.string.none_paired).toString(),"",0));

    }
    //判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
    public static boolean isOpenGPS(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // GPS定位
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 网络服务定位
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        } return false;
    }

   /* private void scanLeDevice(final boolean enable) {
        if(!isOpenGPS(getContext())){
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext(),AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            builder.setTitle("提示")
                    .setMessage("请前往打开手机的位置权限!")
                    .setCancelable(false)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            ((Activity)getContext()).startActivityForResult(intent, 10);
                        }
                    }).show();
            return;
        }
        if (mBtAdapter == null){
            mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        if (mBluetoothLeScanner == null){
            mBluetoothLeScanner = mBtAdapter.getBluetoothLeScanner();
        }
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            scan.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    mScanning = false;
                    enableScan = true;
//                    scan_btn.setText("扫描设备");
                    loading.dismiss();
                    Log.i("SCAN", "stop.....................");
                    mBluetoothLeScanner.stopScan(mScanCallback);
                }
            }, SCAN_PERIOD);
            *//* 开始扫描蓝牙设备，带mLeScanCallback 回调函数 *//*
            Log.i("SCAN", "begin.....................");
            mScanning = true;
            enableScan = false;
//            scan_btn.setText("停止扫描");
            mBluetoothLeScanner.startScan(mScanCallback);
        } else {
            Log.i("Stop", "stoping................");
            mScanning = false;
            mBluetoothLeScanner.stopScan(mScanCallback);
            enableScan = true;
        }

    }*/

    private void init_ble()
    {
        // Initializes Bluetooth adapter.
        mBluetoothLeScanner = mBtAdapter.getBluetoothLeScanner();
        // 打开蓝牙权限
        if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            ((Activity)getContext()).startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

    }

    private void doDiscovery() {
//        setProgressBarIndeterminateVisibility(true);
//        setTitle(R.string.scanning);
        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
        if (this.mBtAdapter.isDiscovering()) {
            this.mBtAdapter.cancelDiscovery();
        }
        this.mBtAdapter.startDiscovery();
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
        if (this.mBtAdapter != null) {
            this.mBtAdapter.cancelDiscovery();
        }
       /* if (!enableScan){
            scanLeDevice(false);
        }*/
        getContext().unregisterReceiver(this.mReceiver);
    }

    @Override
    protected PopupAnimator getPopupAnimator() {
        return new ScrollScaleAnimator(getPopupContentView(), getAnimationDuration(), ScrollAlphaFromTop);
    }


    /*ScanCallback  mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, final ScanResult result) {
            final BluetoothDevice device = result.getDevice();
            String name = device.getName();
            String mac = device.getAddress();
            DeviceBean bean = new DeviceBean(name,mac,device.getType());
            Log.e("getprintLoan",name+":"+device.getAddress()+"=="+device.getType());
            deviceListAdapter.add(bean);
            deviceListAdapter.notifyDataSetChanged();

        }
        @Override
        public void onScanFailed(final int errorCode) {
            super.onScanFailed(errorCode);
            Toast.makeText(getContext(), "扫描出错:"+errorCode, Toast.LENGTH_SHORT).show();
            Log.e("getprintLoan","扫描出错");
        }
    };*/
}
